package dev.pda.display.presentation.splash

import androidx.lifecycle.MutableLiveData
import dev.pda.display.domain.message.MessageRepository
import dev.pda.display.extension.customSubscribe
import dev.pda.display.presentation.common.SchedulerTransformer
import dev.pda.display.presentation.common.base.BaseViewModel
import dev.pda.display.presentation.page.model.ProgramVM
import dev.pda.display.presentation.page.model.ResourceVM
import dev.pda.display.util.mqtt.MqttManager
import javax.inject.Inject

class SplashViewModel @Inject constructor(
    private val messageRepository: MessageRepository,
) : BaseViewModel() {

    companion object{
        private const val subscriptionTopic = "AndroidTopic"
        private const val publishTopic = "AndroidPublishTopic"
    }

    var programVM: ProgramVM? = null
    val resourceVMListLiveData = MutableLiveData<List<ResourceVM>>()

    override fun init() {
        initUDP()
    }

    private fun initUDP() {
        messageRepository.initUDPServer("", 12222)
            .compose(SchedulerTransformer())
            .customSubscribe(
                {
                    initTCP()
                }, {
                    initTCP()
                }
            ).collect()
    }

    private fun initTCP() {
        messageRepository.initTCPServer(12222)
            .compose(SchedulerTransformer())
            .customSubscribe(
                {

                }, {
                }
            ).collect()
    }

    fun parserResourceMessage(message: String) {
        messageRepository
            .getProgramVM(message)
            .compose(SchedulerTransformer())
            .customSubscribe({
                programVM = it
                resourceVMListLiveData.value = it.resources
            }, {

            }).collect()
    }

    fun getProgramWidth(): Int {
        return programVM?.screenWidth?.toInt() ?: 0
    }

    fun getProgramHeight(): Int {
        return programVM?.screenWidth?.toInt() ?: 0
    }

    fun subscribeMQTT(){
        MqttManager.getInstance().subscribe(subscriptionTopic) {

            onSubscriberSuccess {
                //订阅成功
            }

            onSubscriberFailed {
                //订阅失败
            }

            onDeliveryComplete {
                //消息推送完毕
            }

            onConnectionLost {
                //连接已断开
            }
        }
    }

}